package Day_022_T019;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import publicClass.ListNode;

/**
 * 19. 删除链表的倒数第 N 个结点
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 *
 * 进阶：你能尝试使用一趟扫描实现吗？
 *
 *
 *
 * 示例 1：
 *
 *
 * 输入：head = [1,2,3,4,5], n = 2
 * 输出：[1,2,3,5]
 * 示例 2：
 *
 * 输入：head = [1], n = 1
 * 输出：[]
 * 示例 3：
 *
 * 输入：head = [1,2], n = 1
 * 输出：[1]
 *
 *
 * 提示：
 *
 * 链表中结点的数目为 sz
 * 1 <= sz <= 30
 * 0 <= Node.val <= 100
 * 1 <= n <= sz
 *
 * https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
 *
 */
public class T019 {

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode quickPointer = head.next;

        ListNode slowPointer = head;

        int count = 0;

        //第一次遍历 统计链表长度

        while (true){

            if (quickPointer==null){
                break;
            }

            quickPointer = quickPointer.next;
            count++;

        }
        if(count==1){
            return head.next = null;
        }

        if(count==n){
            head = slowPointer.next;
            return head;
        }



        //第二次遍历 找到倒数第n-1个节点的位置

        for (int i = 0; i < count-n; i++) {

            slowPointer = slowPointer.next;

        }


        slowPointer.next = slowPointer.next.next;

        return head;


    }

    public static void main(String[] args) {




        ListNode L1 = new ListNode(1, null);

        ListNode head = new ListNode(0, L1);

        ListNode listNode = removeNthFromEnd(head, 1);

    }

}
